package com.geor.gcv.core.mat;

import java.util.Iterator;
import java.util.List;

import org.opencv.core.Mat;

import com.geor.gcv.core.model.Area;

/**
 * 
 * 根据特定比例合并投影切分结果
 * 
 * @author geor.lusongnan
 *
 */
public class ChsCellChipperImpl extends CellChipperSimpleImpl {

	private float scale;

	public ChsCellChipperImpl() {
		this.scale = 1.1f;
	}

	public ChsCellChipperImpl(float scale) {
		this.scale = scale;
	}

	@Override
	public List<Area> execute(Mat mat) throws Exception {
		List<Area> areas = super.execute(mat);

		modifyCutArea(areas);

		return areas;
	}

	private void modifyCutArea(List<Area> cutAreas) {
		Iterator<Area> it = cutAreas.iterator();
		while (it.hasNext()) {
			Area area = it.next();
			if (area == null) {
				it.remove();
			}
		}

		if (cutAreas.size() == 1) {
			return;
		}
		for (int i = 1; i < cutAreas.size(); i++) {
			Area area1 = cutAreas.get(i - 1);
			Area area2 = cutAreas.get(i);
			Area area = Mats.mergerArea(area1, area2);
			// 判断合并之后的区域是否符合汉字规则
			float width = (float) area.getWidth();
			float height = (float) area.getHeight();
			float val = width / height;
			if (val > this.scale) {
				continue;
			} else {
				cutAreas.set(i - 1, area);
				cutAreas.set(i, null);
				modifyCutArea(cutAreas);
			}
		}
	}

}
